package com.ccx.coachsite.ui.manage;

import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.ccx.coachsite.R;
import com.ccx.coachsite.ui.own.OwerBaseView;
import com.ccx.coachsite.ui.own.OwerMainBase;

public class ManageAddGroupView extends OwerBaseView {

	private Button btnOk;
	private EditText editName;
	private ProgressDialog waitingDialog;
	private InputMethodManager imm;
	private List<ManageGroupInfo> groups;

	public ManageAddGroupView(Context context, OwerMainBase superView) {
		super(context, superView);
	}

	@SuppressWarnings("unchecked")
	public ManageAddGroupView(Context context, OwerMainBase superView,
			Object cinfo) {
		super(context, superView);
		groups = (List<ManageGroupInfo>) cinfo;
		btnOk = (Button) findViewById(R.id.client_group_new_ok);
		editName = (EditText) findViewById(R.id.client_group_name);
		btnOk.setOnClickListener(btnOkClickListener);
		imm = (InputMethodManager) mContext
				.getSystemService(Context.INPUT_METHOD_SERVICE);
	}

	private void onAddSuccess() {
		if (waitingDialog != null) {
			waitingDialog.dismiss();
			waitingDialog = null;
		}
		imm.hideSoftInputFromWindow(editName.getWindowToken(), 0);
		isRefresh = true;
		Toast.makeText(mContext, "添加成功", Toast.LENGTH_SHORT).show();
		mSuperView.onBackClick();
		// SwitchView(ManageKey.ll_manage_group);
	}

	private void onAddFail() {
		if (waitingDialog != null) {
			waitingDialog.dismiss();
			waitingDialog = null;
		}
		Toast.makeText(mContext, "对不起，添加失败，请重试", Toast.LENGTH_SHORT).show();
	}

	OnClickListener btnOkClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (editName.getText().toString().trim().length() <= 0) {
				Toast.makeText(mContext, "分组名称不能为空", Toast.LENGTH_SHORT).show();
				return;
			}
			for (ManageGroupInfo group : groups) {
				if (group.getName()
						.equals(editName.getText().toString().trim())) {
					Toast.makeText(mContext, "该分组名已存在", Toast.LENGTH_SHORT)
							.show();
					return;
				}
			}

			waitingDialog = new ProgressDialog(mContext);
			waitingDialog.setMessage("请稍候");
			waitingDialog.show();
			AddGroupTask task = new AddGroupTask();
			task.execute(editName.getText().toString());
		}
	};

	class AddGroupTask extends AsyncTask<String, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			return ManageProvider.getInstance().addGroup(mContext, params[0]);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (result)
				onAddSuccess();
			else
				onAddFail();
		}
	}
}
